package com.tuling.Util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtils {
    private static final Properties properties = new Properties();
    static {
        // 读取配置文件
        InputStream resourceAsStream = DBUtils.class.getResourceAsStream("/dbonline.properties");

        try {
            // 加载IO流
            properties.load(resourceAsStream);
            // 注册驱动, SPI 会自动发现
//            Class.forName(properties.getProperty("driver"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static Connection getConnection() {
        Connection connection;
        String url = properties.getProperty("url");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        try {
            connection = DriverManager.getConnection(url, username, password);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
